package cn.cvs.utils;

import java.sql.*;

public class BaseDao {

    private static Connection conn = null;

    /**
     * 获取数据库连接
     */
    public static Connection getConnection(){
        String driver = ConfigManager.getInstance().getValue("driver");
        String url = ConfigManager.getInstance().getValue("url");
        String user = ConfigManager.getInstance().getValue("user");
        String password = ConfigManager.getInstance().getValue("password");
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url,user,password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }


    /**
     * 关闭数据库连接
     */
    public static void close(Connection connection, PreparedStatement pstmt, ResultSet rs){
        //关闭结果集
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        //关闭PreparedStatement
        if(pstmt != null){
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        //关闭连接
        if(connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 增、删、改操作
     * @param sql sql语句
     * @param params 参数数组
     * @return 执行结果
     */
    public static int executeUpdate(String sql,Object... params){
        int result = 0;
        conn = getConnection();
        PreparedStatement pstmt = null;
        try{
            pstmt = conn.prepareStatement(sql);
            for(int i=0;i < params.length;i++){
                pstmt.setObject(i+1,params[i]);
            }
            result = pstmt.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            close(null,pstmt,null);
        }
        return result;
    }

    /**
     * 查询操作
     * @param sql sql语句
     * @param params 参数数组
     * @return 查询结果集
     */
    public static ResultSet executeQuery(String sql,Object... params){
        conn = getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try{
            pstmt = conn.prepareStatement(sql);
            for(int i=0;i < params.length;i++){
                pstmt.setObject(i+1,params[i]);
            }
            rs = pstmt.executeQuery();
        }catch (SQLException e){
            e.printStackTrace();
        }
        return rs;
    }
}
